<template>
	<view>
		<map
		      id="map"
		      :latitude="latitude"
		      :longitude="longitude"
		      :scale="scale"
			  :enable-poi="true"
			  :enable-building="true"
			  :show-location="true"
			  :polygons="polygons"
		      style="width: 100%; height: 800rpx;"
		      @tap="handleMapTap"
			  :markers="markers"
			  @markerdrag="handleMarkerDrag"
			  @poitap="onPoiTap"
		      @regionchange="onRegionChange">
		    </map>
			<view>
				<button @click="addVertex">添加顶点</button>
				<button @click="deleteVertex">删除顶点</button>
				<button type="default" @click="completePolygon">完成绘制</button>
			</view>
	</view>
</template>

<script>
	// import AMapLoader from '@amap/amap-jsapi-loader'
	export default {
		data() {
			return {
				latitude: 0,
				  longitude: 0,
				  scale: 16,
				  map: null,
				  isDrawing: true, // 是否正在绘制
				  points: [], // 多边形顶点
				polygons: [], // 多边形数据
				targetPolygon:[],
				 markers: [], // 顶点标记
				 selectedMarkerId: null, // 当前选中的顶点 ID
			}
		},
		onReady() {
			// const path = this.polygon.getPath(); // 获取多边形顶点坐标
			// console.log('多边形顶点坐标:', path)
			this.getLocal()
		    // this.initMap();
		},
		methods: {
			// 更新顶点标记
			updateMarkers() {
			  this.markers = this.points.map((point, index) => ({
				id: index,
				latitude: point.latitude,
				longitude: point.longitude,
				iconPath: "/static/logo.png", // 顶点标记图标
				width: 10,
				height: 10,
				draggable: true, // 允许拖动
			  }));
			},
			// 处理顶点拖动
			handleMarkerDrag(event) {
			  const { markerId, latitude, longitude } = event.detail;
			  this.points[markerId] = { latitude, longitude };
			  this.updatePolygon();
			  this.updateMarkers();
			},
			getLocal(){
				uni.getLocation({
					type: 'wgs84',
					success: (res) =>{
						console.log('res----', res)
						this.latitude = res.latitude
						this.longitude = res.longitude
						this.calculatePoints()
					}
				});
			},
			// 计算四个方向的点
			calculatePoints(){
				const distance = 400; // 距离中心点的距离（米）
				const radius = 6371000; // 地球半径（米）
				// 计算纬度偏移量
				const latOffset = (distance / radius) * (180 / Math.PI);
				// 计算经度偏移量
				const lngOffset = (distance / radius) * (180 / Math.PI) /  Math.cos((this.latitude * Math.PI) / 180);
				this.points = [
					{latitude: this.latitude + latOffset,longitude: this.longitude},
					{latitude: this.latitude - latOffset,longitude: this.longitude},
					{latitude: this.latitude,longitude: this.longitude + lngOffset},
					{latitude: this.latitude,longitude: this.longitude - lngOffset},
				]
				this.updatePolygon();
				this.updateMarkers();
			},
			// 点击地图添加顶点
			handleMapTap(event){
				console.log('handleMapTap-----', event)
				if (!this.isDrawing) return;
				const { latitude, longitude } = event.detail;
				this.latitude = latitude
				this.longitude = longitude
				const index = this.findClosestEdgeIndex({ latitude, longitude });
				  if (index !== -1) {
					this.points.splice(index + 1, 0, { latitude, longitude });
					this.updatePolygon();
					this.updateMarkers();
				  }
			},
			updatePolygon(){
				this.polygons = [
					{
					  points: this.points,
					  strokeWidth: 2,
					  strokeColor: "#FF0000",
					  fillColor: "#FF000022",
					},
				];
				console.log('this.polygons---',this.polygons)
			},
			// 找到最近的边
			findClosestEdgeIndex(point) {
			  let minDistance = Infinity;
			  let closestIndex = -1;
		
			  for (let i = 0; i < this.points.length; i++) {
				const p1 = this.points[i];
				const p2 = this.points[(i + 1) % this.points.length];
				const distance = this.calculateDistanceToEdge(point, p1, p2);
		
				if (distance < minDistance) {
				  minDistance = distance;
				  closestIndex = i;
				}
			  }
		
			  return closestIndex;
			},
			// 计算点到边的距离
			calculateDistanceToEdge(point, p1, p2) {
			      const dx = p2.longitude - p1.longitude;
			      const dy = p2.latitude - p1.latitude;
			      const lengthSquared = dx * dx + dy * dy;
			
			      if (lengthSquared === 0) {
			        return this.calculateDistance(point, p1);
			      }
			
			      const t =
			        ((point.longitude - p1.longitude) * dx +
			          (point.latitude - p1.latitude) * dy) /
			        lengthSquared;
			      const projection = {
			        longitude: p1.longitude + t * dx,
			        latitude: p1.latitude + t * dy,
			      };
			
			      return this.calculateDistance(point, projection);
			},
			// 计算两点之间的距离
			calculateDistance(p1, p2) {
			  const dx = p1.longitude - p2.longitude;
			  const dy = p1.latitude - p2.latitude;
			  return Math.sqrt(dx * dx + dy * dy);
			},
			// 添加顶点
			    addVertex() {
			      if (this.selectedMarkerId !== null) {
			        const point = this.points[this.selectedMarkerId];
			        this.points.splice(this.selectedMarkerId + 1, 0, {
			          latitude: point.latitude,
			          longitude: point.longitude,
			        });
			        this.updatePolygon();
			        this.updateMarkers();
			      }
			    },
			
			    // 删除顶点
			    deleteVertex() {
			      if (this.selectedMarkerId !== null && this.points.length > 3) {
			        this.points.splice(this.selectedMarkerId, 1);
			        this.updatePolygon();
			        this.updateMarkers();
			        this.selectedMarkerId = null;
			      }
			    },
			// 完成绘制
			completePolygon(){
				this.isDrawing = false
			},
			// 视野发生变化时触发
			onRegionChange(){
				
			},
			initMap() {
			    this.map = uni.createMapContext('map', this);
				this.map.initMarkerCluster({
					enableDefaultStyle: false,
					zoomOnClick: true,
					gridSize: 60,
					complete(res) {
					  console.log('initMarkerCluster', res)
					}
				})
			},
		}
	}
</script>
<style>

</style>
